import { defineStore } from "pinia";
import {
    EXAM_START_TIME,
    EXAM_CREATE_TIME,
    EXAM_QUESTIONS,
    EXAM_CORRECT_RATE,
    EXAM_PAPER_TYPE,
} from "@/store/mutation-types";
//import question from '@/mock/question'
import { storage } from "@/utils/Storage";

import {
    getQuestionList
} from "@/api/index";
import { toast } from "@/plugins/toast";
// 做题进度类型
type ProgressType = {
    totalQuestions: number;
    answerCount: number;
};
// 用户答案类型
type UserAnswerType = {
    questionId: string;
    duration: string;
    answer: string;
    isTrue: boolean;
    sectionId: string;
};

export interface IExamState {
    // 开始时间
    startTime: string;
    // 试卷类型 错题本 wrong、收藏collect、练习LEVEL 1-3
    paperType: string;
    // 做题进度
    progress: ProgressType;
    allData: any;
    questionClass: any;
    // 试题列表
    questions: any[];
    // 当前题目ID
    currentQuestionId: string;
    // 当前题目开始时间
    currentQuestionStartTime: number;
    // 用户答案列表
    userAnswerList: UserAnswerType[];

    // 正确率
    correctRate: string;
    // 练习时间
    createTime: string;
}

export const useExamStore = defineStore({
    id: "app-exam",
    state: (): any => ({
        startTime: storage.get(EXAM_START_TIME, ""),
        paperType: storage.get(EXAM_PAPER_TYPE, "1"),
        progress: {
            totalQuestions: 0,
            answerCount: 0,
        },
        allData: {},
        questionClass: {},
        questions: [],
        currentQuestionId: "",
        currentQuestionStartTime: 0,
        userAnswerList: [],
        correctRate: "",
        createTime: "",
        dialogVisible: false,
    }),
    getters: {
        getStartTime(): string {
            return this.startTime;
        },
        getDialogVisible(): boolean {
            return this.dialogVisible;
        },
        getAllData(): any {
            return this.allData;
        },
        getPaperType(): string {
            return this.paperType;
        },
        // 获取做题进度
        getProgress(): ProgressType {
            return this.progress;
        },
        // 获取试题列表
        getQuestionClass(): any {
            return this.questionClass;
        },
        // 获取试题列表
        getQuestions(): any[] {
            return this.questions;
        },
        // 获取当前题目
        getCurrentQuestion(): any {
            if (!this.currentQuestionId) {
                return {};
            }
            let current;
            for (let index = 0; index < this.allData.list.length; index++) {
                current = this.allData.list[index].list.find((question: any) => {
                    if (question.questionType === 1) {
                        return question.id === this.currentQuestionId
                    } else {
                        const qu = question.questionList.find((childqQuestion: any) => {
                            return childqQuestion.id === this.currentQuestionId
                        })
                        return qu;
                    }
                })
                if (current) {
                    index = index += this.allData.list.length;
                }

            }

            if ([2, 3, 5].indexOf(current.questionType) !== -1) {
                current.questionList.forEach((item: any) => {
                    item.showPicker = false;
                })
            }
            return current
        },
        // 获取当前题目ID
        getCurrentQuestionId(): string {
            return this.currentQuestionId;
        },
        // 获取题目序号
        getCurrentQuestionIndex(): number {
            if (!this.currentQuestionId) {
                return 0;
            }
            return this.questions.findIndex(
                (item: any) => {
                    if (item.questionType === 1) {
                        return item.id === this.currentQuestionId
                    } else {
                        return item.questionList.findIndex((childQuestion: any) => childQuestion.id === this.currentQuestionId) !== -1
                    }
                }
            );
        },
        // 获取正确率
        getCorrectRate(): number {
            return Number(this.correctRate);
        },
        //获取练习时间
        getCreateTime(): string {
            return this.createTime;
        },
    },
    actions: {
        // 设置开始时间
        setAllData(data: any) {
            this.allData = data;
        },
        // 设置开始时间
        setstartTime(time: string) {
            this.startTime = time;
            storage.set(EXAM_START_TIME, time);
        },
        setDialogVisible(state: boolean) {
            this.dialogVisible = state;
        },
        // 设置试卷类型
        setPaperType(type: string) {
            this.paperType = type;
            storage.set(EXAM_PAPER_TYPE, type);
        },
        // 切换题目
        setCurrentQuestionId(id: string) {
            this.currentQuestionId = id;
        },
        // 下一题
        nextQuestion() {
            const index = this.getCurrentQuestionIndex;
            if (this.questions[index + 1].questionType == 1) {
                this.setCurrentQuestionId(this.questions[index + 1].id);
            } else {
                this.setCurrentQuestionId(this.questions[index + 1].questionList[0].id);
            }
        },
        // 上一题
        prevQuestion() {
            const index = this.getCurrentQuestionIndex;
            if (index > 0) {
                if (this.questions[index - 1].questionType == 1) {
                    this.setCurrentQuestionId(this.questions[index - 1].id);
                } else {
                    this.setCurrentQuestionId(this.questions[index - 1].questionList[0].id);
                }
            } else {
                toast.warning("已经是第一题了");
            }
        },

        // 下一题
        resultNextQuestion() {
            if (this.getCurrentQuestionId == 40) {
                return;
            }
            if (this.getCurrentQuestion.questionType == 1) {
                this.setCurrentQuestionId(this.getCurrentQuestionId + 1)
            } else {
                this.setCurrentQuestionId(this.getCurrentQuestionId + this.getCurrentQuestion.questionList.length)
            }
        },
        // 上一题
        resultPrevQuestion() {
            if (this.getCurrentQuestionId == 1) {
                return;
            }
            if (this.getCurrentQuestion.questionType == 1) {
                this.setCurrentQuestionId(this.getCurrentQuestionId - 1)
            } else {
                this.setCurrentQuestionId(this.getCurrentQuestionId - this.getCurrentQuestion.questionList.length)
            }

        },
        saveUserAnswer(answer: string) {
            let isTrue = false;
            if (!this.getCurrentQuestionId) {
                return;
            }
            // 更改当前题目的用户答案
            this.questions = this.questions.map((item: any) => {
                if (item.id === this.getCurrentQuestionId) {
                    item.userAnswer = answer;
                }
                return item;
            });

            // 保存用户答案
            const userAnswer = {
                questionId: this.getCurrentQuestionId,
                answer,
                isTrue,
                sectionId: this.getCurrentQuestion.sectionId,
            };
            // 先遍历是否已经保存过该题目的答案
            const index = this.userAnswerList.findIndex(
                (item: any) => item.questionId === this.getCurrentQuestionId
            );
            if (index > -1) {
                this.userAnswerList[index] = userAnswer;
            } else {
                this.userAnswerList.push(userAnswer);
            }
            // 更改做题进度
            this.setProgress();
        },
        // 保存答案
        saveChildrenUserAnswer(answer: string, id: any) {
            this.questions = this.questions.map((item: any) => {
                if (item.questionType === 1) {
                    return item;
                }

                item.questionList.forEach((question: any) => {
                    if (question.id === id) {
                        question.userAnswer = answer;
                    }

                })

                return item;
            });
            this.setProgress();

            // // 保存用户答案
            // const userAnswer = {
            //     questionId: id,
            //     answer,
            // };
            // // 先遍历是否已经保存过该题目的答案
            // const index = this.userAnswerList.findIndex(
            //     (item) => item.questionId === this.getCurrentQuestionId
            // );
            // if (index > -1) {
            //     this.userAnswerList[index] = userAnswer;
            // } else {
            //     this.userAnswerList.push(userAnswer);

            //     // 更改做题进度
            //     this.progress.answerCount++;
            // }
        },



        // 查询做题进度
        setProgress() {
            let totalQuestions = 20, answerCount = 0;
            switch (this.paperType) {
                case '1': // part1
                    const hasAnswerArr = this.questionClass.list.filter((item: any) => {
                        return item.userAnswer && item.userAnswer !== '';
                    });
                    totalQuestions = this.questionClass.list.length;
                    answerCount = hasAnswerArr.length || 0;
                    break;

                default:
                    totalQuestions = 0;
                    answerCount = 0;
                    this.questionClass.list.forEach((item: any) => {
                        if (item.questionType === 1) {
                            totalQuestions++;
                            if (item.hasOwnProperty('userAnswer') && item.userAnswer !== '') {
                                answerCount++;
                            }

                        }
                        if (item.questionType !== 1) {
                            item.questionList.forEach((childQuestion: any) => {
                                totalQuestions++;
                                if (childQuestion.hasOwnProperty('userAnswer') && childQuestion.userAnswer !== '') {
                                    answerCount++;
                                }
                            })
                        }
                    })
                    break;
            }
            this.progress = {
                totalQuestions,
                answerCount,
            };
        },
        // 查询试题列表
        setQuestions() {
            if (!this.allData.hasOwnProperty('list')) {
                return;
            }
            this.questionClass = this.allData.list[+this.getPaperType - 1];
            this.questions = this.questionClass.list;
            this.setCurrentQuestionId(this.questions[0].id || this.questions[0].questionList[0].id);
            this.setProgress();

        },


        // 提交答案
        async submitAnswer() {
            // const res: any = await submitAnswerReq({
            //     id: this.getPaperId,
            // });
            // if (res.correctRate) {
            //     this.correctRate = res.correctRate;
            //     this.createTime = res.createTime;
            //     // 遍历 res.questions，匹配到 this.questions，更新 this.questions
            //     res.questions.forEach((item: any) => {
            //         const index = this.questions.findIndex(
            //             (question) => question.id === item.id
            //         );
            //         if (index > -1) {
            //             this.questions[index] = item;
            //         }
            //     });

            //     // this.questions = res.questions;
            //     // 保存
            //     storage.set(EXAM_QUESTIONS, this.questions);
            //     storage.set(EXAM_CORRECT_RATE, this.correctRate);
            //     storage.set(EXAM_CREATE_TIME, this.createTime);
            //     return true;
            // } else {
            //     return false;
            // }
        },

        // 初始化
        async init() {
            const res = await getQuestionList();
            res.list.forEach((item: any) => {
                item.list = this.extractEnhancedQuestionList(item.list)
            })

            this.setstartTime(new Date().getTime().toString());

            this.setAllData(res);

            this.setQuestions();

        },
        // 初始化结果
        async initResult() {
            this.questions = storage.get(EXAM_QUESTIONS, []);
            this.correctRate = storage.get(EXAM_CORRECT_RATE, "");
            this.createTime = storage.get(EXAM_CREATE_TIME, "");
        },
        // 初始化结果为错题
        async initCorrection() {
            this.correctRate = storage.get(EXAM_CORRECT_RATE, "");
            this.createTime = storage.get(EXAM_CREATE_TIME, "");
            const questions = storage.get(EXAM_QUESTIONS, []);
            this.questions = questions.filter((item: any) => !item.isTrue);
        },


        extractEnhancedQuestionList(data: any) {
            let result: any[] = [];

            data.forEach((part: { [x: string]: any; questionList?: any; }) => {
                if (part.questionType !== 1) {
                    result.push(part);
                    return;
                }
                part.questionList.forEach((question: any) => {
                    // 创建一个新对象，包含当前question的所有属性  
                    let enhancedQuestion = { ...question };

                    // 将当前部分的额外属性（除了questionList）合并到新对象中  
                    Object.keys(part).forEach(key => {
                        if (key !== 'questionList') {
                            enhancedQuestion[key] = part[key];
                        }
                    });

                    // 将增强后的对象添加到结果数组中  
                    result.push(enhancedQuestion);
                });
            });

            return result;
        }
    },
});
